﻿using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Ecobee.Net
{
	/// <summary>
	/// 
	/// </summary>
	public class ApiResult
	{
		public HttpStatusCode StatusCode { get; set; }
		public string ErrorMessage { get; set; }
		public bool Successful { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public Error Error
		{
			get
			{
				Error returnValue = new Error();

				if (!this.Successful)
				{
					returnValue.Deserialize(this.Data);
				}

				return returnValue;
			}
		}

		internal string Data { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public dynamic DataObject
		{
			get
			{
				dynamic returnValue = null;

				if (this.Successful)
				{
					try
					{
						returnValue = JsonConvert.DeserializeObject(this.Data);
					}
					catch
					{
						returnValue = null;
					}
				}

				return returnValue;
			}
		}

		/// <summary>
		/// The API response code.
		/// </summary>
		public Status Status { get; set; }

		internal async Task ProcessResponse(HttpResponseMessage response)
		{
			this.Successful = response.IsSuccessStatusCode;
			this.Data = await response.Content.ReadAsStringAsync();
			this.StatusCode = response.StatusCode;
			this.ErrorMessage = response.ReasonPhrase;

			if (this.DataObject!=null && this.DataObject.status != null)
			{
				this.Status = new Status();
				this.Status.FromDataObject(this.DataObject.status);
			}
		}

		internal void Fail(Exception ex)
		{
			this.Successful = false;
			this.Data = string.Empty;
			this.StatusCode = HttpStatusCode.InternalServerError;
			this.ErrorMessage = ex.Message;
		}
	}
}
